<?php

namespace app\api\middleware;

use dengje\jwt\facade\JWTAuth;

class OrCheck
{
    public function handle($request, \Closure $next)
    {
        $authHeader = $request->header('Authorization');
        $uid = 0;
        if ($authHeader && preg_match('/^Bearer\s+(.+)$/i', $authHeader, $matches)) {
            try {
                $payload = JWTAuth::auth();
            } catch (\Exception $e) { // 捕获token过期
                return error('身份信息已过期！', 401);
                //throw new \think\exception\HttpException(401, '无效 token');
            }
            $uid = $payload['uid'];
        }
        $request->uid = $uid ?? 0;

        return $next($request);
    }
}
